﻿using Atletika.Common;
using Atletika.Helpers;
using Atletika.Shared.Entities;
using Atletika.Shared.Helpers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Hub App template is documented at http://go.microsoft.com/fwlink/?LinkId=321221

namespace Atletika
{
    /// <summary>
    /// Provides application-specific behavior to supplement the default Application class.
    /// </summary>
    sealed partial class App : Application
    {
        public List<Article> Articles { get; set; }
        public List<Competition> Competitions { get; set; }
        
        /// <summary>
        /// Initializes the singleton Application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            this.InitializeComponent();
            this.Suspending += OnSuspending;
        }

        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used such as when the application is launched to open a specific file.
        /// </summary>
        /// <param name="e">Details about the launch request and process.</param>
        protected override async void OnLaunched(LaunchActivatedEventArgs e)
        {
            Exception exception = null;

            try
            {
                bool loadState = (e.PreviousExecutionState == ApplicationExecutionState.Terminated);
                Window.Current.Content = new ExtendedSplash(e.SplashScreen, loadState);
                Window.Current.Activate();

                bool download = false;
                if (ConnectionHelper.ConnectedToInternet())
                {
                    if (this.Articles == null)
                    {
                        this.Articles = await DownloadHelper.GetArticles();
                        download = true;

                    }
                    if (this.Competitions == null)
                    {
                        this.Competitions = await DownloadHelper.GetCompetitions();
                        download = true;
                    }
                }
                else
                {
                    await new MessageDialog("Aplikácii sa nepodarilo pripojiť k zdroju dát.", "Slovenská atletika").ShowAsync();
                    this.Exit();
                }

                if (download)
                {
                    ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
                    localSettings.Values["LastUpdate"] = DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss");
                }

                Frame rootFrame = new Frame();
                Window.Current.Content = rootFrame;
                rootFrame.Navigate(typeof(HubPage)); // show after data is loaded
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            if (exception != null)
            {
                await new MessageDialog("Aplikácii sa nepodarilo načítať údaje.", "Slovenská atletika").ShowAsync();
            }
        }

        /// <summary>
        /// Invoked when Navigation to a certain page fails
        /// </summary>
        /// <param name="sender">The Frame which failed navigation</param>
        /// <param name="e">Details about the navigation failure</param>
        void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
        }

        /// <summary>
        /// Invoked when application execution is being suspended.  Application state is saved
        /// without knowing whether the application will be terminated or resumed with the contents
        /// of memory still intact.
        /// </summary>
        /// <param name="sender">The source of the suspend request.</param>
        /// <param name="e">Details about the suspend request.</param>
        private async void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();
            await SuspensionManager.SaveAsync();
            deferral.Complete();
        }
    }
}
